package logic

import (
	"context"
	"strconv"
	"week1_zg6/orderrpc/model/mysql"

	"week1_zg6/orderrpc/internal/svc"
	"week1_zg6/orderrpc/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type PurchaseOfGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPurchaseOfGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PurchaseOfGoodsLogic {
	return &PurchaseOfGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PurchaseOfGoodsLogic) PurchaseOfGoods(in *order.PurchaseOfGoodsRequest) (*order.PurchaseOfGoodsResponse, error) {

	goods := mysql.WhereGoods(in.ID)
	atoi, err := strconv.Atoi(in.Num)
	if err != nil {
		return nil, err
	}
	if goods.GoodsInventory < int64(atoi) {
		return &order.PurchaseOfGoodsResponse{
			Data: "库存不足",
		}, nil
	}
	err = mysql.UpdateGoods(mysql.Goods{
		ID:             goods.ID,
		GoodsName:      goods.GoodsName,
		GoodsPrice:     goods.GoodsPrice,
		GoodsInventory: goods.GoodsInventory - int64(atoi),
		GoodsViews:     goods.GoodsViews,
	})
	if err != nil {
		return nil, err
	}
	return &order.PurchaseOfGoodsResponse{
		Data: "购买成功",
	}, nil
}
